package com.caiyigo.baihua.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.imageio.ImageIO;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.asprise.util.ocr.OCR;
import com.caiyigo.baihua.model.Xuesheng;

public class ThreadPoolHttpClient {
	// 线程池
	private ExecutorService exe = null;
	// 线程池的容量
	private static final int POOL_SIZE = 1;
	private HttpClient client = null;
	String[] urls = null;

	public ThreadPoolHttpClient() {

	}

	public static void main(String[] args) throws Exception {

		new ThreadPoolHttpClient().test();

	}

	public HttpPost[] getUrls(List<Xuesheng> xueshengs, String pici, String yzm)
			throws UnsupportedEncodingException {
		HttpPost[] s = new HttpPost[xueshengs.size()];
		int i = 0;
		for (Xuesheng xuesheng : xueshengs) {
			HttpPost httppost = new HttpPost(
					"http://query.5184.com/query/zk/zk_seat_" + pici + ".jsp");
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("name0", ""));

			nvps.add(new BasicNameValuePair("rand", yzm));

			nvps.add(new BasicNameValuePair("serChecked", "on"));
			httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			s[i] = httppost;
		}

		return s;
	}

	public String getYzm(HttpClient httpClient) throws ClientProtocolException,
			IOException {

		HttpGet httpget = new HttpGet("http://query.5184.com/query/image.jsp"); // 执行get请求
		HttpResponse response = httpClient.execute(httpget);

		String imgcode = null;
		try {
//			imgcode = new OCR().recognizeEverything(ImageIO.read(response
//					.getEntity().getContent()));
			File file = new File("c:/login.jpg");
			OutputStream ops = new FileOutputStream(file);
			response.getEntity().writeTo(ops);
			ops.close();
			imgcode = new OCR().recognizeEverything(ImageIO.read(file));
			String rand = imgcode.replace("O", "0").replace("i", "1")
					.replace("g", "9").replace("q", "9").replace("G", "9")
					.replace("S", "5").replace("s", "5").replace("B", "8")
					.replace("b", "6").replace("o", "0").replace("l", "1")
					.replace("u", "0").replace("U", "0").replace("Y", "9")
					.trim();
			return rand;
		} catch (Exception e) {

			e.getCause();
			return "1";
		} finally {

		}

	}

	public void test() throws Exception {
		exe = Executors.newFixedThreadPool(POOL_SIZE);
		HttpParams params = new BasicHttpParams();
		/* 从连接池中取连接的超时时间 */
		ConnManagerParams.setTimeout(params, 12000);
		/* 连接超时 */
		HttpConnectionParams.setConnectionTimeout(params, 13000);
		/* 请求超时 */
		HttpConnectionParams.setSoTimeout(params, 12000);
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
				.getSocketFactory()));

		// ClientConnectionManager cm = new
		// PoolingClientConnectionManager(schemeRegistry);
		PoolingClientConnectionManager cm = new PoolingClientConnectionManager(
				schemeRegistry);
		cm.setMaxTotal(10);

		final HttpClient httpClient = new DefaultHttpClient(cm, params);
		String yzm = getYzm(httpClient);
		System.out.println("=============" + yzm);
		// URIs to perform GETs on
		final HttpPost[] urisToGet = getUrls(null, "", yzm.trim());
		// 有多少url创建多少线程，url多时机子撑不住
		// create a thread for each URI
		GetThread[] threads = new GetThread[urisToGet.length];
		for (int i = 0; i < threads.length; i++) {

			threads[i] = new GetThread(httpClient, urisToGet[i]);
		}
		// start the threads
		for (int j = 0; j < threads.length; j++) {

			threads[j].start();
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// join the threads，等待所有请求完成
		for (int j = 0; j < threads.length; j++) {
			threads[j].join();
		}
		// 使用线程池
		// for (int i = 0; i < urisToGet.length; i++) {
		// final int j = i;
		// System.out.println(j);
		// exe.execute(new GetThread(httpClient, urisToGet[i]));
		// }

		// 创建线程池，每次调用POOL_SIZE

		exe.shutdown();
		System.out.println("Done");
	}

	static class GetThread extends Thread {
		Logger logger = Logger.getLogger(GetThread.class);
		private final HttpClient httpClient;
		private final HttpContext context;
		private final HttpPost httpget;

		public GetThread(HttpClient httpClient, HttpPost httpget) {
			this.httpClient = httpClient;
			this.context = new BasicHttpContext();
			this.httpget = httpget;
		}

		@Override
		public void run() {
			this.setName("threadsPoolClient");

			get();
		}

		public void get() {
			try {
				HttpResponse response = this.httpClient.execute(this.httpget,
						this.context);
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					Document document = Jsoup.parse(
							EntityUtils.toString(entity), "GBK");
					Elements trs = document.select("tr");
					if (trs.size() > 0) {
						logger.info(this.httpget.getURI() + ": status"
								+ response.getStatusLine().toString()
								+ "trs.size():" + trs.size() + "内容："
								+ trs.html());
					}
				}
				// ensure the connection gets released to the manager
				EntityUtils.consume(entity);
			} catch (Exception ex) {
				this.httpget.abort();
			} finally {
				httpget.releaseConnection();
			}
		}
	}

}